package com.nxu.admin.controller;

import com.nxu.admin.bean.City;
import com.nxu.admin.bean.Dept;
import com.nxu.admin.bean.User;
import com.nxu.admin.service.CityService;
import com.nxu.admin.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Author wen
 * Date 2021-11-15
 */
@Slf4j
@Controller
public class indexController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    DeptService deptService;

    @Autowired
    CityService cityService;

    @GetMapping("/city")
    @ResponseBody
    public City getCityById(@RequestParam("id") Long id){
        return cityService.getCityById(id);
    }

    @GetMapping("/dept")
    @ResponseBody
    public Dept getById(@RequestParam("id") Long id){
        return deptService.getById(id);
    }

    @ResponseBody
    @PostMapping("/city")
    public City saveCity(City city){
        cityService.saveCity(city);
        return city;
    }

    @GetMapping("/sql")
    @ResponseBody
    public String queryFromDb(){
        Long result = jdbcTemplate.queryForObject("select count(*) from tab_dept", Long.class);
        return result.toString();
    }

    @GetMapping(value = {"/","/login"})
    public String loginPage(){
        return "login";
    }

    @PostMapping("/login")
    public String main(User user, HttpSession session,Model model){
        if(StringUtils.hasLength(user.getUsername()) && "123456".equals(user.getPassword())){
            //System.out.println(user);
            //把登录成功的用户保存起来
            session.setAttribute("loginUser",user);
            //登录成功重定向到main.html:重定向防止表单重复提交
            //System.out.println(session.getAttribute("loginUser"));
            return "redirect:/main.html";
        }else{
            model.addAttribute("msg","账号或密码错误");
            //回到登陆页
            return "login";
        }
    }

    /**
     * 去main页面
     * @return
     */
    @GetMapping("/main.html")
    public String mainPage(HttpSession session,Model model){
        log.info("当前方法是：{}","mainPage");
//        //是否登录。
//        Object loginuser = session.getAttribute("loginUser");
//        if(loginuser != null){
//            return "main";
//        }else{
//            //回到登陆页
//            model.addAttribute("msg","请重新登录");
//            return "login";
//        }
        return "main";
    }
}
